define(['config', 'text!app/module/system/goods.html', 'laypage',
        'mydialog', 'autocomplete', 'jqGrid', 'common', 'ztree', 'ztreecheck',
		'css!app/assets/lib/ztree/css/demo.css',
		'css!app/assets/lib/ztree/css/zTreeStyle/zTreeStyle.css'
	],
	function(config, viewHTML, laypage, mydialog, autocomplete, jqGrid,
		common, ztree, ztreecheck) {
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

		var grid_url = "/api/goods";
		var model = avalon.define({
			$id:"goods",
			query:{
				name:"",
			},
			goodsInfo:{
				id,
				name,
				model,
				typeId,
				floorPrice,
				describe,
				remarks,
				item,
				createUser,
				createTime
			},
//			ars: [{
//				key: "无效",
//				val: false
//			}, {
//				key: "有效",
//				val: true
//			}],
			init: function(){
				//alert("ss");
				model.loadGrid();
				model.addEvent();
			},
//			aaa: function(){
//				alert("ss");
//			},
			loadGrid:function(){
				function t(val ,opt,row){
					
					var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb"  title="修改"><a href="javascript:void();" /></span><span class="fa fa-trash-o mrb"  title="删除"></span></div>'
					avalon.log(html_con)
					return html_con;
				};
				
				var i = Public.setGrid();
				$("#grid").jqGrid({
					//token验证
					loadBeforeSend: function(jqXHR) {
						jqXHR.setRequestHeader(
							"X-AuthToken", token);
					},
					datatype: "JSON",
					mtype: "POST",
					url: grid_url + "/list",
					postData: model.query.$model,
					//高
					height: i.h,
					//设置jqGrid显示为斑马线样式。就是隔行用不同的背景色区分开
					altRows: true,
					//表格左侧将添加一用于显示行数（从1开始）的列
					rownumbers: true,
					//多选
					multiselect: true,
					//只有点击checkbox时该行才被选中，点击其他列，将清除当前行的选中
					multiboxonly: true,
					//起始页
					page: 1,
					//排序列的名称，此参数会被传到后台
					sortname: "id",
					//排序方式：降序
					sortorder: "desc",
					//定义翻页用的导航栏，必须是有效的html元素
					pager: "#page",
					//在grid上显示记录条数
					rowNum: 10,
					//一个下拉选择框，用来改变显示记录数
					rowList: [10, 30, 50],
					//是否要显示总记录数信息
					viewrecords: true,
					//用来说明当初始化列宽度时候的计算类型，:
					//ture，按比例初始化列宽度
					//false,列宽度使用colModel指定的宽度
					shrinkToFit: false,
					//ture:调整列宽度不会改变表格的宽度,shrinkToFit 为false时，此属性会被忽略
					forceFit: false,
					//描述json 数据格式的数组
					jsonReader: {
						root: "data.list",
						//只读属性，定义了返回的记录数
						records: "data.totalRow",
						//总页数
						total: "data.totalPage",
						repeatitems: false,
						//行id
						id: "id"
					},
					colModel:[{
							name: "operation",
							label: "操作",
							formatter: t,
							align: "center",
							width: '60px',
							title: false
						},
						{
							name: "id",
							label: "ID",
							align: "center",
							width: '50px',
							title: false,
							hidden:true
						},
						{
							name: "name",
							label: "设备名称",
							align: "center",
							width: '66px',
							title: false
						},
						{
							name: "model",
							label: "规格",
							align: "center",
							width: '66px',
							title: false
						},
						{
							name: "typeId",
							label: "类型id",
							align: "center",
							width: '66px',
							title: false,
							hidden：true
						},
						{
							name: "floortPrice",
							label: "单价",
							align: "center",
							width: '66px',
							title: false
						},
						{
							name: "retailprice",
							label: "建议零售价",
							align: "center",
							width: '66px',
							title: false
						},
						{
							name: "describe",
							label: "描述",
							align: "center",
							width: '66px',
							title: false
						},
						{
							name: "remarks",
							label: "备注",
							align: "center",
							width: '66px',
							title: false
						}
					],
					cmTemplate: {
						sortable: false,
						title: false
					},
					loadError: function() {
						Public.tips({
							type: 2,
							content: "加载数据出现异常！"
						})
					},
					ondblClickRow: function(t) {
						model.view(t);
					},
					
				});
				
			},
			
			//提交
			reloadData: function() {

				$("#grid").jqGrid("setGridParam", {
					url: grid_url + "/list",
					datatype: "json",
					mtype: 'POST',
					postData: model.query.$model
				}).trigger("reloadGrid");
			},
			//重置
			reset: function() {
				model.query = {
					name: ""
				};
				model.reloadData();
			},
			//添加或更新
			edit:function(goodsInfo){
				//alert("sss");
				if(goodsInfo === -1){
					model.goodsInfo={
						id,
						name,
						model,
						typeId,
						floorPrice,
						describe,
						remarks,
						item,
						createUser,
						createTime
					};
					
					var url = "/api/goods/save";
					
					dialog({
						title:'添加商品信息',
						content:$("#editGoods"),
						okValue:"确定",
						ok:function(){
//							model.goodsInfo.status = model.goodsInfo.status ;
							//提交修改
							$.ajax({
								type:"POST",
								url:url,
								contentType: "application/json",
								data:JSON.stringify(model.goodsInfo),
								beforeSend: function(xhr) {
									xhr.setRequestHeader("X-AuthToken", token);
								},
								success: function(data, status, xhr) {
									avalon.log(data);
									model.reset();
								},
								error: function(responseData, textStatus, errorThrown) {
									alert(JSON.stringify(responseData) );
//									alert("Failed: " +
//										responseData);
								}
								
							});
							
							//非空校验
							var goodsUuid = document.getElementById("goodsUuid").value ;
							var goodsSku = document.getElementById("goodsSku").value ;
							var goodsName = document.getElementById("goodsName").value ;
							if (goodsUuid == ""|| goodsUuid.indexOf(" ") >=0) {
								alert("uuid不能为空");
								return false;
							} ;
							if (goodsSku ==""|| goodsSku.indexOf(" ") >=0) {
								alert("sku不能为空");
								return false;
							} ;
							if (goodsName == "" || goodsName.indexOf(" ") >=0) {
								alert("品名不能为空");
								return false;
							} ;
						},
						cancelValue: "取消",
						cancel: function() {}
					}).showModal();
					
					
				}
				else{
					
					model.goodsInfo = goodsInfo;
					var url = "/api/goods/update";
					dialog({
						title: '修改商品信息',
						content: $("#editGoods"),
						okValue: "确定",
						ok: function() {
//							model.goodsInfo.status = model.goodsInfo.status;
							// 提交修改
							$.ajax({
								type: "POST",
								url: url,
								contentType: 'application/json',
								data: JSON.stringify(model.goodsInfo),
								beforeSend: function(xhr) {
									xhr.setRequestHeader("X-AuthToken", token);
								},
								success: function(data, status, xhr) {
									model.reset();
								},
								error: function(responseData, textStatus, errorThrown) {
									alert(JSON.stringify(responseData) );
//									alert("Failed: " +responseData);
									
								}

							});
							
							//非空校验
//							var goodsUuid = document.getElementById("goodsUuid").value ;
							var goodsSku = document.getElementById("goodsSku").value ;
							var goodsName = document.getElementById("goodsName").value ;
//							if (goodsUuid == ""|| goodsUuid.indexOf(" ") >=0) {
//								alert("uuid不能为空");
//								return false;
//							} ;
							if (goodsSku ==""|| goodsSku.indexOf(" ") >=0) {
								alert("sku不能为空");
								return false;
							} ;
							if (goodsName == "" || goodsName.indexOf(" ") >=0) {
								alert("品名不能为空");
								return false;
							} ;

						},
						cancelValue: "取消",
						cancel: function() {}
					}).showModal();
				}
			},
			
			
			//删除商品
			del: function(ids){
				var url = grid_url +"/delete";
				avalon.log(ids);
				dialog({
					title: '删除商品信息',
					content: '确定删除吗',
					okValue: "确定",
					
					ok : function(){
						//删除
						$.ajax({
							type:"POST",
							url:url,
							data:{
								"ids":ids
							},
							beforeSend: function(xhr) {
								xhr.setRequestHeader("X-AuthToken", token);
							},
							success: function(data, status, xhr) {
								avalon.log(data);
								model.reset();
							},
							error: function(responseData, textStatus, errorThrown) {
								alert("Failed: " + responseData);
							}
						});
						//$.post(url, $("#userForm").serialize());
					},
					cancelValue: "取消",
					cancel: function() {}
				}).showModal();
			},
			
			addEvent: function(){
				//提交
				$("#search").click(function(e){
					//先阻止浏览器默认跳转行为
					e.preventDefault();
					model.reloadData();
				});
				
				//重置
				$("#resets").click(function(e){
					e.preventDefault();
					model.reset();
					model.reloadData();
				});
				
				//修改
				$(".grid-wrap").on("click", ".fa-edit", function() {
					var i = $(this).parent().data("id");
					model.edit($("#grid").getRowData(i));
				});

				//删除
				$(".grid-wrap").on("click", ".fa-trash-o",function() {
					var i = $(this).parent().data("id");
					avalon.log(i);
					model.del(i);
				});
					
				//多项删除
				$("#delete").click(
					function(e) {
						e.preventDefault();
						var t = $("#grid").jqGrid("getGridParam", "selarrrow");
						t.length ? model.del(t.join()) : Public.tips({
							type: 2,
							content: "请选择要删除的人员！"
						});
	
					});
					
			},
			
			 
			 
		});
		function errorDialog(data) {
			var mydialog = dialog({
				title: "错误",
				content: "操作失败！",
				okValue: "确定",
				ok: function() {}
			});
			return mydialog;
		}

		function successDialog() {
			var mydialog = dialog({
				title: "成功",
				content: "操作成功！",
				okValue: "确定",
				ok: function() {}
			});
			return mydialog;
		}
		
		// 定义视图模块
		var viewmod = {
			viewtSrc: viewHTML,
			viewInit: function() {
				model.init();
			}, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
			viewDestroy: function() {} // 切换菜单时销毁原来的view
		};
		return viewmod;
		
		
	});